package com.eastseeway.radioproject.unlock;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.work.Data;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;

import com.eastseeway.radioproject.BuildConfig;
import com.eastseeway.radioproject.base.BaseViewModel;
import com.eastseeway.radioproject.entities.BaseResponse;
import com.eastseeway.radioproject.entities.FirmwareUpdateState;
import com.eastseeway.radioproject.entities.OperationParams;
import com.eastseeway.radioproject.entities.UserInfo;
import com.eastseeway.radioproject.entities.VersionBean;
import com.eastseeway.radioproject.utils.FileTransferManager;
import com.eastseeway.radioproject.utils.SPHelper;
import com.eastseeway.radioproject.utils.TransferProgress;
import com.eastseeway.radioproject.views.SingleLiveEvent;
import com.eastseeway.radioproject.work.FirmwareUpgradeWork;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.Deque;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentLinkedQueue;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UnlockViewModel extends BaseViewModel<UnlockRepository> {
    private final StringBuilder sb = new StringBuilder();
    private final WorkManager mWorkManager;
    private MutableLiveData<String> password = new MutableLiveData<>();
    private final MutableLiveData<String> username = new MutableLiveData<>();
    private final Deque<VersionBean> tasks = new ConcurrentLinkedDeque<>();
    private final MutableLiveData<FirmwareUpdateState> firmwareUpdateState = new MutableLiveData<>();
    private final MutableLiveData<WorkInfo> mFirmwareUpgradeWorkInfo = new MutableLiveData<>();
//    private final MutableLiveData<Integer> timeoutFlag = new MutableLiveData<>();
    private final MutableLiveData<String> toastInfo = new MutableLiveData<>();

    public UnlockViewModel(@NonNull Application application) {
        super(application);
        createFile();
        mWorkManager = WorkManager.getInstance(application);
//        Log.e("12121", "fileName " + fileName);
    }

    @Override
    protected UnlockRepository setRepository() {
        return new UnlockRepository();
    }

    /**
     * 点击了哪个键的回调
     * @param s
     */
    public void onPasswordChange(String s){
        switch (s){
            case "ok":
                break;
            case "delete":
                if (sb.length() > 0) {
                    sb.deleteCharAt(sb.length() - 1);
                    password.setValue(sb.toString());
                }
                break;

            default:
                if (sb.length() < 6) {
                    sb.append(s);
                    password.setValue(sb.toString());
                }
        }
    }

//    private int generateRandomNumber() {
//        SecureRandom random = new SecureRandom();
//        return random.nextInt(2001); // 生成0-2000的随机数
//    }
//
//    public void setTimeoutFlag(){
//        timeoutFlag.setValue(generateRandomNumber());
//    }
//    public MutableLiveData<Integer> getTimeoutFlag() {
//        return timeoutFlag;
//    }

    LiveData<UserInfo> queryUser(String username){
        return mRepository.queryUserByUsername(username);
    }
    LiveData<UserInfo> queryAdmin(){return mRepository.queryAdmin();}
    LiveData<List<UserInfo>> queryAllUsers(){
        return mRepository.queryAllUsers();
    }
    LiveData<List<VersionBean>> queryAllVersions(){
        return mRepository.queryAllVersion();
    }
    void insertAdmin(){
        mRepository.insertAdmin();
    }

    public MutableLiveData<String> getUsername() {
        return username;
    }
    public String queryVersionCodeByAddress(String address){
        return mRepository.queryVersionCodeByAddress(address);
    }

    public void insertVersionInfo(VersionBean versionBean){
        mRepository.insertVersionInfo(versionBean);
    }

    public void queryOperationParams(){
        mRepository.queryOperationParams("admin").observeForever(operationParams -> {
            Log.e("12121","unlock operationParams:"+new Gson().toJson(operationParams));
        });
    }

    protected void getLocation(){
        if (isDeviceIdInvalid()) {
            return;
        }
        mRepository.getLocationAddress(getApplication());
    }

    protected void checkFirmwareUpdate(){
//      检查设备码是否录入
        if (isDeviceIdInvalid()) {
            toastInfo.setValue("请先绑定设备");
            return;
        }
//        检查是否有更新任务
//        getFirmwareUpdateState().setValue(FirmwareUpdateState.QUERYING);
        mRepository.checkAppUpdate(SPHelper.getDeviceId(getApplication()), new Callback<BaseResponse<List<VersionBean>>>() {
            @Override
            public void onResponse(@NonNull Call<BaseResponse<List<VersionBean>>> call, @NonNull Response<BaseResponse<List<VersionBean>>> response) {
                if (response.body().isSuccess()) {
                    List<VersionBean> versionBeans = response.body().getResult();
                    Log.e("12121","查询结果："+new Gson().toJson(versionBeans));
                    if (versionBeans.isEmpty()) {
                        return;
                    }
                    VersionBean androidVersionBean = null;
                    tasks.clear();
                    for (VersionBean versionBean : versionBeans) {
                        String softStyle = versionBean.getSoftStyle();
                        switch (softStyle) {
                            case "android":
                                if (!versionBean.getSoftVer().equals(mRepository.queryVersionCodeByAddress(softStyle))) {
                                    androidVersionBean = versionBean;
                                }
                                break;
//                                底板更新比较特殊，放在最后一个进行升级
                            case "bottom_board":
                                if (!versionBean.getSoftVer().equals(mRepository.queryVersionCodeByAddress(softStyle))) {
                                    tasks.offerLast(versionBean);
                                }
                                break;
                            default:
//                                Log.e("12121","999 "+versionBean.getSoftVer());
//                                Log.e("12121","888 "+mRepository.queryVersionCodeByAddress(softStyle));
                                if (!versionBean.getSoftVer().equals(mRepository.queryVersionCodeByAddress(softStyle))) {
                                    tasks.offerFirst(versionBean);
                                }
                                break;
                        }
                    }

                    if (androidVersionBean != null) {
                        executeSingleTask(androidVersionBean);
                    }else if (!tasks.isEmpty()) {
                        updateFirmware();
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call<BaseResponse<List<VersionBean>>> call, @NonNull Throwable throwable) {
            }
        });
    }

    void executeSingleTask(VersionBean versionBean){
        getFirmwareUpdateState().setValue(FirmwareUpdateState.DOWNLOADING);
        Data inputData = new Data.Builder().putString("version_info", new Gson().toJson(versionBean)).build();
        OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(FirmwareUpgradeWork.class)
                .setInputData(inputData)
                .build();
        mWorkManager.enqueue(request);
        mWorkManager.getWorkInfoByIdLiveData(request.getId()).observeForever(new Observer<WorkInfo>() {
            @Override
            public void onChanged(WorkInfo workInfo) {
                mFirmwareUpgradeWorkInfo.postValue(workInfo);
                if (workInfo != null && workInfo.getState().isFinished()) {
                    mWorkManager.getWorkInfoByIdLiveData(request.getId()).removeObserver(this);
                }
            }
        });
    }

    void updateFirmware() {
//        获取任务栈中的第一个任务
        VersionBean task = tasks.poll();
        if (task == null) {
            Log.e("12121","任务栈为空 ");
            getFirmwareUpdateState().setValue(FirmwareUpdateState.ALL_COMPLETED);
//            getIsUpgrading().setValue(false);
        } else {
//            getIsUpgrading().setValue(true);
            Log.e("12121","任务栈不为空 "+new Gson().toJson(task));
            executeSingleTask(task);
        }
    }

    void uploadVersionInfos(String versionInfo){
        if (isDeviceIdInvalid()) {
            return;
        }
        mRepository.uploadVersionInfos(SPHelper.getDeviceId(getApplication()),versionInfo,new Callback<BaseResponse<String>>() {
            @Override
            public void onResponse(@NonNull Call<BaseResponse<String>> call, @NonNull Response<BaseResponse<String>> response) {

            }
            @Override
            public void onFailure(@NonNull Call<BaseResponse<String>> call, @NonNull Throwable throwable) {
            }
        });
    }

    protected void createFile() {mRepository.createFile();}
    public LiveData<WorkInfo> getFirmwareUpgradeWorkInfo() {return mFirmwareUpgradeWorkInfo;}

    public MutableLiveData<FirmwareUpdateState> getFirmwareUpdateState() {
        return firmwareUpdateState;
    }

    public MutableLiveData<String> getToastInfo() {return  toastInfo;}
    public MutableLiveData<String> getPassword() {return password;}

}
